import { MenuItem } from "./ContexMenu";
import { MainWindow } from "../../window/MainWindow";

class ComboBoxItem extends MenuItem {
	// may be change a skin.
}

function AddHistoryArray(s: string, values: string[]): void {
	values.remove(s);
	values.unshift(s);
	if (values.length > 10) {
		values.pop();
	}
}

export class ComboBox extends eui.Component {
	input: eui.TextInput;

	btnDown: eui.Image;

	values: string[] = [];

	constructor() {
		super();
		this.skinName = 'ComboxSkin';
	}

	closeDown(): void{
		this.btnDown.visible = false;
	}

	childrenCreated(): void{
		super.childrenCreated();
		this.input.touchEnabled = false;
		this.btnDown.addEventListener(
			egret.TouchEvent.TOUCH_TAP,
			this.onTapDown,
			this,
		);
	}

	removeCurValue(): void{
		const { text } = this.input;
		this.values.remove(text);
	}

	setValues(values: string[], sel = 0): void{
		this.values = values || [];
		this.input.text = this.values[sel];
	}

	onTapDown(): void{
		if (!this.values || this.values.length === 0) return;

		const menu = MainWindow.ins().contexMenu.showContexMenu(
			this.values,
			this.onContexSelect,
			this,
			this.width,
		);

		const sheight = menu.stage.stageHeight;
		const swidth = menu.stage.stageWidth;
		// menu.y += this.height; // add input.height!
		menu.x += this.width;
		if (menu.x + menu.width > swidth) {
			menu.x = swidth - this.width - menu.width;
		}
		const h = menu.getMenuHeight();

		if (menu.y + h > sheight) {
			// ui.msglog('menu.height', h);
			const y = menu.y - (h + this.height);
			if (y > 0) {
				menu.y = y;
			} else {
				menu.y = sheight - h;
			}
			// menu.y -= h + this.height;
		}
	}

	static evtTextChange = 'EVT_COMBOX_CHANGE';

	onContexSelect(text: string): void{
		this.input.text = text;
		this.dispatchEventWith(ComboBox.evtTextChange, true, { text });
	}

	getValue(): string {
		return this.input.text;
	}

	setValue(s: string): void {
		this.input.text = s;
	}

	RecordValue(): void{
		const s = this.input.text;
		AddHistoryArray(s, this.values);
	}
}

